<?php

require_once realpath('..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'bootstrap.php');
$request = Bike_Service_Locator::getService('Request');
$userManager = Bike_Service_Locator::getService('UserManager');
if($userManager->getCurrentUser() == $userManager->getAnonymous()){
	header('Content-Type: application/json');
	$result = array('success' => 'false', 'msg' => 'Error');
	echo json_encode($result);
	die();
}

define('BIKE_FILE_BROWSER_NEW_FOLDER_NAME', 'new_folder');
define('BIKE_FILE_BROWSER_THUMBS_FOLDER', '.thumbs');
define('BIKE_FILE_BROWSER_DEFAULT_FOLDER_PRIVILEGES', 0777);
define('BIKE_FILE_BROWSER_DEFAULT_FILE_PRIVILEGES', 0666);
define('BIKE_FILE_BROWSER_THUMBS_WIDTH',100);
define('BIKE_FILE_BROWSER_THUMBS_HEIGHT',100);
define('BIKE_FILE_BROWSER_NO_THUMB_TEXT', 'No thumb');

header('Content-Type: application/json');

function returnError($message = ''){
	$result = array(
		'success' => false,
		'error' => $message,
		'message' => $message,
		'items' => array(),
		'total' => 0,
	);
	die(json_encode($result));
}

function getNoThumb(){
	header ('Content-Type: image/png');
	$im = imagecreate(50, 12);
	imagecolorallocate($im, 255, 255, 255);
	$text_color = imagecolorallocate($im, 128, 128, 128);
	imagestring($im, 2, 0, 0,  BIKE_FILE_BROWSER_NO_THUMB_TEXT, $text_color);
	imagepng($im);
	imagedestroy($im);
	die();
}

$request = Bike_Service_Locator::getService('Request');
$action = $request->getRequestVar('action');
$folder = trim($request->getRequestVar('folder'), BIKE_WEB_DIRECTORY_SEPARATOR);
$images_only = (bool) intval($request->getRequestVar('imageBrowser'));
$path = realpath(BIKE_HTML_ROOT . DIRECTORY_SEPARATOR . $folder);

$allowedExtensions = array();
if(!empty($images_only)){
	$allowedExtensions = array('jpg', 'jpeg', 'gif', 'png');
}

if(!empty($path)){
	$path .= DIRECTORY_SEPARATOR;
}

if(strpos($path, BIKE_UPLOAD_DIR) !== 0){
	returnError('Incorrect root folder');
}

function recursiveRemoveDirectory($folder){
	if (!is_dir($folder)) {
		return false;
	}
	$flag = true;
	$files = glob( $folder . DIRECTORY_SEPARATOR . '*', GLOB_MARK );
	foreach( $files as $file ){
		if(is_dir($file)) {
			$flag = $flag && recursiveRemoveDirectory($file);
		} else {
			$flag = $flag && unlink($file);
		}
	}
	//Trying to delete thumbs folder
	recursiveRemoveDirectory($folder . DIRECTORY_SEPARATOR . BIKE_FILE_BROWSER_THUMBS_FOLDER);
	if (is_dir($folder)) $flag = $flag && rmdir($folder);
	return $flag;
}


switch ($action) {
	case 'get_folderlist' :
		$data=array();
		if (is_dir($path)) {
			$dirs = glob($path . '*', GLOB_ONLYDIR);
			foreach($dirs as $dir){
				$subDirs = glob($dir. DIRECTORY_SEPARATOR. '*', GLOB_ONLYDIR);
				if (0 === strpos($dir, '.')) {
					continue;
				}
				$data[] = array(
					'id' => str_replace(BIKE_HTML_ROOT, '', $dir),
					'basename' => trim(basename($dir, DIRECTORY_SEPARATOR)),
					'text' => substr(strrchr($dir, DIRECTORY_SEPARATOR), 1),
					'loaded' => sizeof($subDirs)==0,
					'expanded' => false
				);
			}
			echo json_encode($data);
		}
		break;

	case 'get_filelist' :
		$data=array('data' => '', 'count'=> 0);
		if (is_dir($path)) {
			foreach (new DirectoryIterator($path) as $file){
				if($file->isDot() || $file->isDir() || substr($file->getFilename(), 0, 1) == '.') {
					continue;
				}
				$pathInfo = pathinfo($file->getFileName());
				if(!empty($allowedExtensions) && !(in_array(strtolower($pathInfo['extension']), $allowedExtensions) && getimagesize($file->getPathname()))) {
					continue;
				}
//				if (! is_allowed_filename($file->getFileName())) {
//					continue;
//				}
				$item = array(
					'name' => $file->getFileName(),
					'size' => $file->getSize(),
					'mtime' => $file->getMTime(),
					'web_path'=> BIKE_WEB_DIRECTORY_SEPARATOR . str_replace(DIRECTORY_SEPARATOR, BIKE_WEB_DIRECTORY_SEPARATOR, trim($folder,BIKE_WEB_DIRECTORY_SEPARATOR)) . BIKE_WEB_DIRECTORY_SEPARATOR . $file->getFileName()
				);
				if ($request->getRequestVar('mode') == 'thumbs') {
					$thumb_name = $path . BIKE_FILE_BROWSER_THUMBS_FOLDER . DIRECTORY_SEPARATOR . $file->getFileName() .'.png';
					if (is_file($thumb_name) && $file->getMTime() < filemtime($thumb_name)) {
						$item['thumb_path'] = str_replace(array(BIKE_HTML_ROOT, DIRECTORY_SEPARATOR), array(DIRECTORY_SEPARATOR, BIKE_WEB_DIRECTORY_SEPARATOR), $thumb_name);
					} else {
						if(file_exists($thumb_name)){
							unlink($thumb_name);
						}
					}
				}
				$data['data'][] = $item;

			}
			$data['count'] = sizeof($data['data']);
		}
		echo json_encode($data);
		break;

	case 'folder_new' :
		if (is_dir($path)) {
			$dirs = glob($path . BIKE_FILE_BROWSER_NEW_FOLDER_NAME . '*', GLOB_ONLYDIR);
			$newFolderPath = rtrim(str_replace(BIKE_WEB_DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
			$newFolderName = BIKE_FILE_BROWSER_NEW_FOLDER_NAME;
			if(!empty($dirs)){
				$lastNewDir = array_pop($dirs);
				$lastNewDir = trim(str_replace(array($path, BIKE_FILE_BROWSER_NEW_FOLDER_NAME), '', $lastNewDir), DIRECTORY_SEPARATOR);
				$lastFolderNameSymbol = 0;
				if(0 != strlen($lastNewDir)){
					$lastFolderNameSymbol = intval(substr($lastNewDir, 0, 1));
				}
				$newFolderName .= ($lastFolderNameSymbol + 1);
			}
			$newFolderPath .= $newFolderName;
			if (mkdir($newFolderPath, BIKE_FILE_BROWSER_DEFAULT_FOLDER_PRIVILEGES)) {
				echo json_encode(array('success'=>true,'folder'=> $folder,'id'=> $folder . BIKE_WEB_DIRECTORY_SEPARATOR . $newFolderName));
			} else {
				echo json_encode(array('success'=>false));
			}
		}
		break;

	case 'folder_rename' :
		$renameFolderTo = $request->getRequestVar('name');
		;
		if(!empty($renameFolderTo) && !preg_match('#[^a-z0-9\.]+$#i', $renameFolderTo) && !empty($folder) && is_dir($path)){
			$newFolderName =  dirname($path) . DIRECTORY_SEPARATOR . $renameFolderTo;
			if($newFolderName && 0 === strpos($newFolderName, BIKE_UPLOAD_DIR) && rename($path, $newFolderName)){
				chmod($newFolderName, BIKE_FILE_BROWSER_DEFAULT_FOLDER_PRIVILEGES);
				echo json_encode(array('success' => true, 'folder' => '/' . $folder,'id' => str_replace(BIKE_HTML_ROOT, '', $newFolderName)));
			}else{
				echo json_encode(array('success'=>false));
			}
		}
		break;

	case 'folder_delete' :
		if(is_dir($path) && !empty($folder)){
			if(recursiveRemoveDirectory($path)){
				echo json_encode(array('success'=>true,'folder'=> $folder));
			}else{
				echo json_encode(array('success'=>false));
			}
		}
		break;

	case 'file_rename' :
		$name = $request->getRequestVar('name');
		$oldName = $request->getRequestVar('oldName');
		$realPath = realpath($path . $oldName);
		if(!empty($realPath) && 0 === strpos($realPath, BIKE_UPLOAD_DIR) && is_readable($realPath)){
			if (rename($realPath, $path . $name)) {
				echo json_encode(array('success'=>true, 'folder' => DIRECTORY_SEPARATOR . $folder,'id' => $name));
			} else {
				echo json_encode(array('success'=>false));
			}
		}
		break;

	case 'file_delete' :
		$file = $request->getRequestVar('file');
		$realPath = realpath($path . $file);
		if (!empty($file) && !empty($realPath) && 0 === strpos($realPath, BIKE_UPLOAD_DIR)) {
			if (unlink($realPath)) {
				echo json_encode(array('success' => true, 'folder' => BIKE_WEB_DIRECTORY_SEPARATOR . $folder));
			} else {
				echo json_encode(array('success'=>false));
			}
		}
		break;

	case 'file_download' :
		$file = $request->getRequestVar('file');
		$realPath  = realpath($path . $file);
		if(!empty($file) && !empty($realPath) && 0 === strpos($realPath, BIKE_UPLOAD_DIR)){
			header('Content-Type: application/x-download');
			header('Content-Disposition: attachment; filename="' . $file . '";');
			header('Content-Length: ' . filesize($realPath));
			echo file_get_contents($realPath);
			die();
		}else{
			returnError('Incorrect filename');
		}
		break;

	case 'file_upload' :
		header('Content-Type: text/html');
		$uploadHandler  = new Bike_File_Upload($path, $allowedExtensions);
		try{
			$fileName = $uploadHandler->upload('file');
			if('WIN' != strtoupper(substr(PHP_OS, 0, 3))){ // wtf? on win file become read-only after uploading
				chmod($fileName, BIKE_FILE_BROWSER_DEFAULT_FILE_PRIVILEGES);
			}
			echo json_encode(array('success'=>true, 'file' => str_replace(array($path, DIRECTORY_SEPARATOR), array('', BIKE_WEB_DIRECTORY_SEPARATOR), $fileName) ,'folder'=> BIKE_WEB_DIRECTORY_SEPARATOR . str_replace(DIRECTORY_SEPARATOR, BIKE_WEB_DIRECTORY_SEPARATOR, $folder)));
		}catch(Bike_File_Upload_Exception $e){
			returnError($e->getMessage());
		}
		break;

	case 'get_thumb' :
		$file = $request->getRequestVar('file');
		$realPath = realpath($path . $file);
		if (!empty($realPath)&& 0 === strpos($realPath, BIKE_UPLOAD_DIR) && is_file($realPath) && is_readable($realPath)) {
			$thumbsFolder = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . BIKE_FILE_BROWSER_THUMBS_FOLDER;
			$sourceFile = realpath($path. $file);
			$extImages = array('jpg', 'jpeg', 'gif', 'png');
			if (file_exists($sourceFile)) {
				$sourceInfo = pathinfo($sourceFile);
				if(!in_array($sourceInfo['extension'], $extImages)){
					getNoThumb();
					break;
				}
				if (!file_exists($thumbsFolder)) {
					if (!mkdir($thumbsFolder, BIKE_FILE_BROWSER_DEFAULT_FOLDER_PRIVILEGES)) {
						getNoThumb();
						break;
					}
				}
				$is = getimagesize($sourceFile);
				if ($is) {
					$sourceWidth = $is[0];
					$sourceHeight = $is[1];
					$sourceImage = @imagecreatefromstring(file_get_contents($sourceFile));
					if ($sourceImage){
						$sourceRatio = $sourceWidth / $sourceHeight;
						$width = BIKE_FILE_BROWSER_THUMBS_WIDTH;
						$height = BIKE_FILE_BROWSER_THUMBS_HEIGHT;
						if ($width / $height > $sourceRatio) {
						   $width = ceil($height * $sourceRatio);
						} else {
						   $height = ceil($width / $sourceRatio);
						}
						if($sourceWidth < $width && $sourceHeight < $height) {
							$width = $sourceWidth;
							$height = $sourceHeight;
						}
						$image = @imagecreatetruecolor($width, $height);
						imagefill($image,0,0,imagecolorallocate($image,255,255,255));
						imagecopyresampled($image, $sourceImage, 0, 0, 0, 0, $width, $height, $sourceWidth, $sourceHeight);
						$imageName = rtrim($thumbsFolder, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file . '.png';
						if (imagepng($image, $imageName, 5)){
							if('WIN' != strtoupper(substr(PHP_OS, 0, 3))){ // wtf? on win file become read-only after uploading
								@chmod($imageName, BIKE_FILE_BROWSER_DEFAULT_FILE_PRIVILEGES);
							}
							header('Location: '. str_replace(array(BIKE_HTML_ROOT, DIRECTORY_SEPARATOR), BIKE_WEB_DIRECTORY_SEPARATOR, $imageName));
							exit();
						}
					}
				}
			}
		}
		getNoThumb();
		break;
}